package org.meetunexpectedly.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.meetunexpectedly.constant.RedisConstant;
import org.meetunexpectedly.entity.vo.Result;
import org.meetunexpectedly.entity.user.User;
import org.meetunexpectedly.holder.IPHolder;
import org.meetunexpectedly.holder.UserHolder;
import org.meetunexpectedly.service.user.UserService;
import org.meetunexpectedly.util.JwtUtils;
import org.meetunexpectedly.util.RedisCacheUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description: 用户信息拦截器
 * @Author: pupil
 * @Date: 2024/08/11 下午 7:11
 */
@Component
public class UserInterceptor implements HandlerInterceptor {

    // 用于将 Java 对象转换为 JSON 字符串
    private ObjectMapper objectMapper = new ObjectMapper();

    private UserService userService;

    private UserHolder userHolder;

    private RedisCacheUtil redisCacheUtil;

    public UserInterceptor(UserService userService,RedisCacheUtil redisCacheUtil) {
        this.userService = userService;
        this.redisCacheUtil = redisCacheUtil;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 检测是否为跨源资源共享请求
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }

        // 判断token是否有效
        if (!JwtUtils.checkToken(request)) {
            // 返回响应消息给前端
            return response(Result.error().message("请登录后再操作"), response);
        }

        Long userId = JwtUtils.getUserId(request);
        User user = userService.getById(userId);
        // 判断用户是否存在
        if (ObjectUtils.isEmpty(user)) {
            // 返回响应消息给前端
            return response(Result.error().message("用户不存在"), response);
        }

        // 用户上线(优化前)
        // UserOnlineHolder.userOnline(userId);
        // 用户上线(优化后)
        redisCacheUtil.set(RedisConstant.USER_ONLINE + userId, userId, RedisConstant.USER_ONLINE_TIME);
        // 将请求的ip添加到共享变量中
        IPHolder.set(request);
        // 将用户id添加到共享变量中
        UserHolder.set(userId);
        return true; // 放行

    }

    /**
     * 创建响应消息
     *
     * @param result   响应结果
     * @param response HttpServletResponse
     * @return
     * @throws IOException
     */
    private boolean response(Result result, HttpServletResponse response) throws IOException {
        // 设置响应头
        response.setHeader("Access-Control-Allow-Origin", "*"); // 允许来自任何源的跨域请求
        response.setHeader("Cache-Control", "no-cache"); // 设置消息不缓存
        response.setCharacterEncoding("UTF-8"); // 消息编码
        response.setContentType("application/json"); // 消息内容类型
        // 设置响应体
        response.getWriter().println(objectMapper.writeValueAsString(result));
        response.getWriter().flush();
        return false;
    }
}
